<template>
  <view class="container">
    <!-- 用户信息设置 -->
    <view class="user-box">
      <div class="user-item">
        <span>头像</span>
        <div class="item-right" @click="changeImage">
          <image :src="userInfo.avater" mode="scaleToFill" />
          <span class="iconfont icon-arrow-right"></span>
        </div>
      </div>
      <navigator url="./updatename" open-type="navigate">
        <div class="user-item">
          <span>昵称</span>
          <div class="item-right">
            <span>
              {{ userInfo.nick_name ? userInfo.nick_name : "请输入昵称" }}
            </span>
            <span class="iconfont icon-arrow-right"></span>
          </div>
        </div>
      </navigator>
      <div class="user-item">
        <span>ID</span>
        <span class="user-id">{{ userInfo.id }}</span>
      </div>
    </view>
    <!-- 绑定信息 -->
    <view class="bind-box">
      <div class="bind-item">
        <span>手机号</span>
        <div class="item-right">
          <button
            class="phone-btn"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
          >
            获取手机号
          </button>
        </div>
      </div>
      <div class="bind-item">
        <span>QQ</span>
        <div class="item-right">
          <span>未绑定</span>
          <span class="iconfont icon-arrow-right"></span>
        </div>
      </div>
      <div class="bind-item">
        <span>微博</span>
        <div class="item-right">
          <span>未绑定</span>
          <span class="iconfont icon-arrow-right"></span>
        </div>
      </div>
    </view>
  </view>
</template>

<script>
//在需要解密的页面引用该文件
import WXBizDataCrypt from "@/common/WXBizDataCrypt.js";
import { mapState, mapMutations } from "vuex";
const {
  changeUsersInfo,
  getUserInfo,
  getUserMsg,
} = require("@/api/user/setting");

export default {
  props: {},
  components: {},
  data() {
    return {};
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  watch: {},
  methods: {
    ...mapMutations(["editUserInfo"]),

    // 获取用户数据
    getData() {
      let openid = uni.getStorageSync("openId");
      if (!openid) return;

      // 获取用户数据
      getUserInfo({ openid }).then(res => {
        this.editUserInfo(res);
      });
    },

    // 修改头像
    changeImage() {
      if (uni.getStorageSync("openId") == "")
        return uni.showToast({ title: "未登录不能进行操作！", icon: "none" });
      uni.chooseImage({
        //从本地相册选择图片或使用相机拍照
        count: 1, // 默认9
        sizeType: ["original", "compressed"], // original compressed 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: res => {
          if (!res.tempFilePaths.length > 0) return;
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          this.userInfo.avater = res.tempFilePaths[0];

          // 文件名
          let cloudPath = uni.getStorageSync("openId") + Date.now() + ".jpg";
          uniCloud.uploadFile({
            filePath: this.userInfo.avater, // 要上传的文件对象
            cloudPath, // 文件的绝对路径，包含文件名
            //上传进度回调
            onUploadProgress: progressEvent => {
              // 进度
              var percentCompleted = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
              );
            },
            success(res) {
              // 更新用户头像图片路径
              changeUsersInfo({
                openid: uni.getStorageSync("openId"),
                avater: res.fileID,
              }).then(
                res => {
                  console.log("更新成功！");
                },
                err => {
                  uni.showToast({ title: err, icon: "none" });
                }
              );
            },
            fail(err) {
              console.log(err);
            },
          });
        },
      });
    },
    // 获取手机号
    getPhoneNumber(PhoneNumber) {
      let appid = "wx69baeab338b75925"; //小程序ID
      let secret = "91a436a8f9a4405e4e6c35c339ea9b61"; //小程序密钥
      //调用 wx.login 接口,获取code
      uni.login({
        success: res => {
          getUserMsg({ code: res.code }).then(res => {
            // 解密用户信息;
            let dataCrypt = new WXBizDataCrypt(appid, res.session_key);
            let data = dataCrypt.decryptData(
              PhoneNumber.detail.encryptedData,
              PhoneNumber.detail.iv
            );
            console.log(data);
            // //data就是最终解密的用户信息
            // countryCode: "86"  区号
            // phoneNumber: "15634123456"  用户绑定的手机号（国外手机号会有区号）
            // purePhoneNumber: "15634123456"  没有区号的手机号
            // watermark:
            // appid: "wxce185cd1da123456"
            // timestamp: 1607906868
          });
        },
        fail: err => {
          console.log(err);
        },
      });
    },
  },
  created() {
    // 获取用户数据
    this.getData();
  },
  onShow() {},
  mounted() {},
  beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.user-box,
.bind-box {
  display: flex;
  flex-direction: column;
  margin-top: 10rpx;
  font-size: 28rpx;

  .user-item,
  .bind-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100rpx;
    padding: 0 30rpx;
    background-color: #fff;
    border-bottom: 2rpx solid #f7f8fe;

    &:last-child {
      border-bottom: none;
    }

    .item-right {
      display: flex;
      align-items: center;
    }

    .item-right > image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
    }

    .item-right > span {
      color: #999999;
      font-size: 28rpx;

      &:last-child {
        margin-left: 4rpx;
        font-size: 40rpx;
      }
    }

    .user-id {
      color: #333;
    }

    .phone-btn {
      width: 180rpx;
      height: 48rpx;
      border: 2rpx solid #666ee8;
      border-radius: 8rpx;
      line-height: 48rpx;
      text-align: center;
      color: #666ee8;
    }
  }
}

.bind-box {
  margin-top: 20rpx;
}
</style>
